package com.aiyige.utils;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

import com.aiyige.R;

public class MaxHeightRecyclerView extends RecyclerView {
    private int mMaxHeight = -1;

    private AttributeSet attrs;
    private Context context;
    public MaxHeightRecyclerView(Context context) {
        super(context);
        initialize(context, null);
    }

    public MaxHeightRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initialize(context, attrs);
    }

    public MaxHeightRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initialize(context, attrs);
    }


    private void initialize(Context context, AttributeSet attrs) {
        this.context = context;
        this.attrs = attrs;
        if (attrs != null) {
            TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightRecyclerView);
            mMaxHeight = arr.getLayoutDimension(R.styleable.MaxHeightRecyclerView_maxHeightRv_maxHeight, mMaxHeight);
            arr.recycle();
        }
    }

    public void setMaxHeight(int maxHeight) {
        mMaxHeight = maxHeight;
        if (attrs != null && context != null) {
            initialize(context,attrs);
        }
        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mMaxHeight > 0) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(mMaxHeight, MeasureSpec.AT_MOST);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

}
